package com.fyt.ZhongYaoApp.config;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {

    /**
     * 预处理回调方法，实现处理器预处理
     * 返回值：true表示继续流程；false表示流程中断，不会继续调用其他的拦截器或者处理器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从http请求头key为Authorization中取出JWT
        String JWTtoken = request.getHeader("Authorization");
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("ZhongYaoApp")).build();
        try {
            // 1.校验JWT字符串
            DecodedJWT decodedJWT = jwtVerifier.verify(JWTtoken);
            // 2.如果用到Redis存用户信息的话，那么取出JWT字符串载荷中的随机token，从Redis中获取用户信息
            // ...
            return true;
        }catch (SignatureVerificationException e){
            returnJson(response,"无效签名");
            e.printStackTrace();
        }catch (TokenExpiredException e){
            returnJson(response,"token已经过期");
            e.printStackTrace();
        }catch (AlgorithmMismatchException e){
            returnJson(response,"算法不一致");
            e.printStackTrace();
        }catch (Exception e){
            returnJson(response,"token无效");
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 返回格式化后的json到前端页面
     *
     * @param response
     * @param message
     * @throws Exception
     */
    private void returnJson(HttpServletResponse response, String message) throws Exception{
        PrintWriter writer = null;
        // 注意点1：这边返回配置为josn格式
        response.setContentType("application/json;charset=UTF-8");
        try {
            Map<String, Object> result = new HashMap<>();
            result.put("state", "false");
            result.put("msg", message);
            writer = response.getWriter();
            // 注意点2，这样要用fastjson转换一下后，返回的前端才是格式化后的json格式
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}

